<?php

namespace app\web\controller;

use app\common\controller\Api;
use app\common\model\OrderSupplement as OrderSupplementM;
use app\common\service\AddService;
use app\common\service\OrdinaryService;
use app\common\service\ReceiverService;
use think\Db;
use think\Validate;

/**
 * 补录单控制器
 * @package app\index\controller
 */
class OrderSupplement extends Auth
{
    public $noNeedLogin = [];

    /**
     * 补录单列表
     */
    public function lists()
    {
        $getData = $this->request->post();
        $rule = [
            'page' => 'require',
            'limit' => 'require',
        ];
        $msg = [
            'page.require' => '缺少页码',
            'limit.require' => '缺少每页条数',
        ];
        $validate = Validate::make($rule, $msg);
        $result = $validate->check($getData);
        if (!$result) {
            $this->result($validate->getError(), '', 204);
        }
        $data = Db::name('qt_order_supplement')
            ->field('os.*,r.name as room_name,p.name as project_name,u.real_name as open_room_name,hand.name as hand_card_name')
            ->alias('os')
            ->leftJoin('qt_room r','r.id = os.room_id')
            ->leftJoin('qt_project p','p.id = os.project_id')
            ->leftJoin('qt_users u','u.id = os.open_room_id')
            ->leftJoin('qt_hand_card hand','hand.id = os.hand_card')
            ->where(['os.store_id'=>$this->userInfo['store_id'],'os.status'=>'1'])
            ->paginate($getData['limit'])->each(function ($item){
                $item['create_order_name'] = Db::name('qt_users')->where(['id'=>$item['create_order_id']])->value('real_name');
                if(!empty($item['engineer_id'])){
                    $userIds = explode(',',$item['engineer_id']);
                    $engineerData = Db::name('qt_users')->whereIn('id',$userIds)->column('work_number');
                    $item['engineer_name'] = implode(',',$engineerData);
                }else{
                    $item['engineer_name'] = '';
                }
                return $item;
            });
        $this->result('查询成功', $data, 200);

    }



    /**
     * 添加补录单
     */
    public function add()
    {
        $getData = $this->request->post();
        if(empty($getData['hand_card']))$getData['hand_card'] = null;
        if(empty($getData['number']))$getData['number'] = 1;
        if(empty($getData['create_order_id']))$getData['create_order_id'] = null;
        $rule = [
            'engineer_id' => 'require',
            'room_id' => 'require|number',
            'project_id' => 'require|number',
            'order_type' => 'require|number',
            'open_room_id' => 'require|number',
        ];
        $msg = [
            'engineer_id.require' => '技师号必须填写',
            'room_id.require' => '房间必须填写',
            'room_id.number' => '房间格式不正确',
            'project_id.require' => '项目必须填写',
            'project_id.number' => '项目格式不正确',
            'order_type.require' => '上钟类型必须填写',
            'order_type.number' => '上钟类型不正确',
            'open_room_id.require' => '开房人必须填写',
            'open_room_id.number' => '开房人格式不正确',
        ];
        $validate = Validate::make($rule, $msg);
        $result = $validate->check($getData);
        if (!$result) {
            $this->result($validate->getError(), '', 204);
        }
        $getData['create_time'] = time();
        $getData['store_id'] = $this->userInfo['store_id'];
        //处理手牌号
        if(isset($getData['hand_card']) && !empty($getData['hand_card'])){
            $handCardId  = Db::name('qt_hand_card')
                ->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['hand_card']])
                ->value('id');
            $getData['hand_card'] = $handCardId;
        }
        if(OrderSupplementM::create($getData)){
            $this->result('添加成功', '', 200);
        }else{
            $this->result('添加失败', '', 204);
        }
    }


    /**
     * 修改补录单
     */
    public function edit()
    {
        $getData = $this->request->post();
        if(empty($getData['hand_card']))$getData['hand_card'] = null;
        if(empty($getData['number']))$getData['number'] = 1;
        if(empty($getData['create_order_id']))$getData['create_order_id'] = null;
        $rule = [
            'id' => 'require',
            'engineer_id' => 'require',
            'room_id' => 'require|number',
            'project_id' => 'require|number',
            'order_type' => 'require|number',
            'open_room_id' => 'require|number',
        ];
        $msg = [
            'id.require' => '缺少补录单',
            'engineer_id.require' => '技师号必须填写',
            'room_id.require' => '房间必须填写',
            'room_id.number' => '房间格式不正确',
            'project_id.require' => '项目必须填写',
            'project_id.number' => '项目格式不正确',
            'order_type.require' => '上钟类型必须填写',
            'order_type.number' => '上钟类型不正确',
            'open_room_id.require' => '开房人必须填写',
            'open_room_id.number' => '开房人格式不正确',
        ];
        $validate = Validate::make($rule, $msg);
        $result = $validate->check($getData);
        if (!$result) {
            $this->result($validate->getError(), '', 204);
        }
        //处理手牌号
        if(isset($getData['hand_card']) && !empty($getData['hand_card'])){
            $getData['hand_card'] = Db::name('qt_hand_card')->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['hand_card']])->value('id');
        }
        $getData['create_time'] = time();
        $model = new OrderSupplementM();
        if($model->save($getData,['id'=>$getData['id']])){
            $this->result('修改成功', '', 200);
        }else{
            $this->result('修改失败', '', 204);
        }
    }



    /**
     * 删除补录单
     */
    public function del()
    {
        $getData = $this->request->post();
        $rule = ['id' => 'require'];
        $msg = ['id.require' => '缺少补录单'];
        $validate = Validate::make($rule, $msg);
        $result = $validate->check($getData);
        if (!$result) {
            $this->result($validate->getError(), '', 204);
        }
        if(OrderSupplementM::destroy($getData['id'])){
            $this->result('删除成功', '', 200);
        }else{
            $this->result('删除失败', '', 204);
        }
    }


    /**
     * 确认补录单
     */
    public function confirm(){
        $getData = $this->request->post();
        $rule = ['ids' => 'require',];
        $msg = ['ids.require' => '缺少补录单合集',];
        $validate = Validate::make($rule, $msg);
        $result = $validate->check($getData);
        if (!$result) {
            $this->result($validate->getError(), '', 204);
        }
        $ids = explode(',',$getData['ids']);
        foreach ($ids as $key=>$value){
            $data = OrderSupplementM::get($value);
            $roomData = Db::name('qt_room')->where(['id'=>$data['room_id']])->find();
            if($roomData['status_id'] != '10'){
                $roomStatus = '4';
            }else{
                $roomStatus = '10';
            }
            $engineerData = explode(',',$data['engineer_id']);
            $projectData = Db::name('qt_project')->where(['id'=>$data['project_id']])->find();
            $totalPrice = count($engineerData) * $data['number'] * $projectData['price'];
            $totalNum = count($engineerData) * $data['number'];
            //查询房间是否有订单
            $roomOrder = Db::name('qt_order')
                ->where(['store_id'=>$this->userInfo['store_id'],'room_id'=>$data['room_id'],'pay_status'=>'1'])
                ->find();
            if (empty($roomOrder)) {
                $order['order_no'] = ordersn();
                $order['store_id'] = $this->userInfo['store_id'];
                $order['room_id'] = $data['room_id'];
                $order['hand_card_id'] = $data['hand_card'];
                $order['total_num'] = $totalNum;
                $order['total_price'] = $totalPrice;
                $order['status'] = '1';
                $order['delay'] = 0;
                $order['time_type'] =1;
                $order['created_time'] = time();
                $orderId = Db::name('qt_order')->insertGetId($order);
            } else {
                $orderId = $roomOrder['id'];
            }
            if($data['number'] > 1){
                for($i = 1;$i<= $data['number'];$i++){
                    foreach ($engineerData as $k=>$v){
                        $orderProject = [
                            'name' => $projectData['name'],
                            'created_order_id' => $data['create_order_id'],
                            'engineer_id' => $v,
                            'order_id' => $orderId,
                            'project_id' => $data['project_id'],
                            'room_id' => $data['room_id'],
                            'hand_card_id' => $data['hand_card'],
                            'order_type' => $data['order_type'],
                            'num' => '1',
                            'price' => $projectData['price'],
                            'store_id' => $projectData['store_id'],
                            'creater_room' => $data['open_room_id'],
                            'sale_id' => $data['open_room_id'],
                            'message' => '2',
                            'is_broadcast' => '2',
                            'is_add_clock' => '2',
                            'created_time' => time(),
                            'is_add' => '1',
                            'start_time' => time(),
                            'real_end_time' => time(),
                            'end_time' => time(),
                        ];
                        $orderProjectId = Db::name('qt_order_project')->insertGetId($orderProject);
                        $orderType = $data['order_type'];
                        $isAdd = '1';
                        if($data['order_type'] == '6'){
                            $orderType = '1';
                            $isAdd = '2';
                        }
                        if($data['order_type'] == '7'){
                            $orderType = '2';
                            $isAdd = '2';
                        }
                        $commission = 0;
                        //普通提成
                        if ($isAdd == '1') {
                            $commission = new OrdinaryService();
                            $commission = $commission->showCommission($orderProject['order_type'], $isAdd, $projectData);
                        }
                        //加班提成
                        if ($isAdd == '2') {
                            $commission = new AddService();
                            $commission = $commission->showCommission($orderProject['order_type'],$isAdd, $projectData);
                        }
                        //计算接待提成
                        $receiver = new ReceiverService();
                        $receiver = $receiver->showCommission($orderProject['order_type'], $isAdd, $projectData);
                        if ($this->storeInfo['floor_commission_type'] == '1') {
                            $cashierId = $data['create_order_id'];
                        } else {
                            $cashierId = $data['open_room_id'];
                        }
                        if($commission == null){
                            $commission = 0;
                        }
                        $insert = [
                            'store_id' => $this->storeInfo['id'],
                            'cashier_id' => $cashierId,//接待人
                            'user_id' => $v,//技师
                            'room_id' => $orderProject['room_id'],
                            'money' => $orderProject['price'],
                            'commission' => $commission,//技师提成
                            'receiver' => $receiver,//接待提成
                            'product_id' => $orderProject['project_id'],
                            'type' => '1',
                            'created_time' => time(),
                            'is_pay' => '1',
                            'order_project_id' => $orderProjectId,
                            'status' => $orderType,
                            'is_add' => $isAdd,
                        ];
                        Db::name('qt_commission_log')->insert($insert);
                        //修改订单状态
                        Db::name('qt_order_project')
                            ->where(['id' => $orderProjectId])
                            ->update(['engineer_id' => $v, 'return_time' => null,'order_type'=>$orderType,'is_add'=>$isAdd ]);
                        //更新房间订单号
                        Db::name('qt_room')->where(['id' => $orderProject['room_id']])->update(['order_id' => $orderProjectId, 'status_id' => $roomStatus]);

                    }
                }
            }

            Db::name('qt_order_supplement')->where(['id'=>$value])->update(['status'=>'2']);
        }
        $this->result('确认成功', '', 200);
    }

}
